﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace SCG.General
{
    public partial class StateButton : Button
    {
        //events
        public event EventHandler<EventArgs> DownStateChanged;

        //constructor
        public StateButton()
        {
            FlatStyle = FlatStyle.Flat;
            BackColor = Color.Black;
            ForeColor = Color.White;
            BackColorDown = Color.Green;
            InitializeComponent();
            _oldBackColor = BackColor;
        }

        //The back color when the button is depressed
        public Color BackColorDown { get; set; }

        //Is it a toggle on off button?
        public bool Toggle { get; set; }

        //The group index allows the button to turn off other ones in the group
        public int GroupIndex { get; set; }

        //The down state of the button
        public bool Down
        {
            get
            {
                return BackColor == BackColorDown;
            }
            set
            {
                bool isDown = BackColor == BackColorDown;
                if (isDown != value)
                {
                    if (value)
                    {
                        BackColor = BackColorDown;
                        PushUpOtherButtonsInGroup();
                    }
                    else
                        BackColor = _oldBackColor;
                    if (DownStateChanged != null)
                        DownStateChanged(this, EventArgs.Empty);
                }
                Refresh();
            }
        }

        //Private members
        private Color _oldBackColor;

        //Override click - set down state
        protected override void OnClick(EventArgs e)
        {
            base.OnClick(e);

            //Allow toggle
            if (!Down || Toggle)
                Down = !Down;
        }

        //Push up all the other buttons in the group
        private void PushUpOtherButtonsInGroup()
        {
            foreach(Control ctl in Parent.Controls)
                if (ctl != this)
                    if (ctl is StateButton)
                    {
                        StateButton other = ctl as StateButton;
                        if (other.GroupIndex == GroupIndex)
                            other.Down = false;
                    }
        }
    }
}
